<template>
  <view class="add-car">
    <up-toast ref="uToast" />
    <image class="bg-logo" src="@/static/image/logo_bg.png"  />
    <view class="topbar" :style="topbarStyle">
      <view class="topbar-returnBtn" @click="handleReturnPage">
        <up-icon name="arrow-left" color="white" size="24"></up-icon>
        <text class="topbar-returnBtn-text">返回</text>
      </view>
      <view class="topbar-title">车辆录入</view>
    </view>
    <view class="main" :style="mainStyle">
      <view class="driving-license">
        <view class="driving-license-title" >
          <text class="driving-license-title-left">行驶证正副本</text>
          <text v-if="!hasCameraAuth" class="driving-license-title-right" @click="handleOpenCameraAuth">相机权限被关闭，点击重新打开</text>
        </view>
        <view v-if="drivingLicenseImg" class="driving-license-upload-img">
          <image
            :class="isVerticalImg ? 'verticalImg' : 'horizontalImg'"
            :src="drivingLicenseImg"
            @click.stop="handlePreviewOrTabkePhoto"
          />
          <ycy-action-sheet ref="actionSheetRef" :actions="actionSheetOption" @select="handleActionSheetSelect" />
        </view>
        <view v-else class="driving-license-upload">
          <view @click.stop="handleTakePhoto">
            <view class="driving-license-upload-img-placeholder">
              <image class="driving-license-upload-img-placeholder-item" mode="aspectFit" src="@/static/image/driving_license_1.png" />
              <image class="driving-license-upload-img-placeholder-item" mode="aspectFit" src="@/static/image/driving_license_2.png" />
            </view>
            <ycy-camera-icon class="driving-license-upload-icon" />
          </view>
        </view>
      </view>
      <up-form ref="formRef" labelWidth="120" :model="formData" :rules="formRules" errorType="toast">
        <up-form-item label="车牌号" prop="licensePlate" required borderBottom>
          <template #right>
            <view @click.stop="handleOpenlicensePlatePopup">
              <up-input v-model="formData.licensePlate" readonly inputAlign="right" placeholder="请输入车牌号" border="none" />
            </view>
            <ycy-license-plate-popup ref="licensePlatePopupRef" v-model:value="formData.licensePlate" />
          </template>
        </up-form-item>
        <up-form-item label="车辆类型" prop="carType" borderBottom>
          <template #right>
            <up-input v-model="formData.carType" inputAlign="right" placeholder="请输入车辆类型" border="none" />
          </template>
        </up-form-item>
        <up-form-item label="所有人" prop="owner" borderBottom>
          <template #right>
            <up-input v-model="formData.owner" inputAlign="right" placeholder="请输入所有人" border="none" />
          </template>
        </up-form-item>
        <up-form-item label="使用性质" prop="useNature" borderBottom>
          <template #right>
            <ycy-picker v-model:value="formData.useNature" :columns="useNatureOptions">
              <up-input
                v-model="formData.useNature[0]"
                disabled
                disabledColor="#ffffff"
                inputAlign="right"
                placeholder="请选择使用性质"
                border="none"
              />
            </ycy-picker>
          </template>
        </up-form-item>
        <up-form-item label="品牌型号" prop="brandModel" borderBottom>
          <template #right>
            <up-input v-model="formData.brandModel" inputAlign="right" placeholder="请输入品牌型号" border="none" />
          </template>
        </up-form-item>
        <up-form-item label="车辆识别代码" prop="identificationCode" borderBottom>
          <template #right>
            <up-input v-model="formData.identificationCode" inputAlign="right" placeholder="请输入车辆识别代码" border="none" />
          </template>
        </up-form-item>
        <up-form-item label="发动机号码" prop="engineCode" borderBottom>
          <template #right>
            <up-input v-model="formData.engineCode" inputAlign="right" placeholder="请输入发动机号码" border="none" />
          </template>
        </up-form-item>
        <up-form-item label="注册时间" prop="registerTime" required borderBottom>
          <ycy-datetime-picker v-model:value="formData.registerTime" title="注册时间" placeholder="请选择注册时间" />
        </up-form-item>
        <up-form-item label="核载人数" prop="peopleNum" borderBottom>
          <template #right>
            <up-input v-model="formData.peopleNum" inputAlign="right" type="number" placeholder="请输入核载人数" border="none" />
          </template>
        </up-form-item>
        <up-form-item label="是否有伤亡事故" prop="casualtyAccident" borderBottom>
          <template #right>
            <up-switch v-model="formData.casualtyAccident" :inactiveValue="0" :activeValue="1" activeColor="#125796"></up-switch>
          </template>
        </up-form-item>
        <up-form-item label="上次年检时间" prop="lastCheckTime" borderBottom>
          <template #right>
            <ycy-datetime-picker v-model:value="formData.lastCheckTime" title="年检时间" placeholder="请选择上次年检时间" />
          </template>
        </up-form-item>
      </up-form>
    </view>
    <button class="bottom-btn" @click="handleSubmit">提交</button>
  </view>
</template>

<script setup>
  import { ref, reactive, computed } from 'vue';
  import { onLoad, onShow } from '@dcloudio/uni-app';
  import API from '@/api'
	
	onShow(() => {
    uni.getSetting({
      success(res) {
        if(res.authSetting['scope.camera']) hasCameraAuth.value = true;
        else hasCameraAuth.value = false;
      }
    })
    console.log('show hasCameraAuth', hasCameraAuth.value);
	})

  onLoad(async options => {
    // 行驶证识别：从拍摄行驶证的页面carCamera跳转过来，携带drivingLicenseImg参数
		if (options.drivingLicenseImg) {
      drivingLicenseImg.value = options.drivingLicenseImg;
      await identifyDrivingLicense();
    }

    // 车辆编辑：携带车辆的id参数
    if (options.carId) await getDetail(options.carId);

    // 从车辆详情页跳转过来，添加完后跳转回新添加的车辆详情
    if (options.fromPage) fromPage.value = options.fromPage;

    checkIsVerticalImg();
    console.log('onload', hasCameraAuth.value, drivingLicenseImg.value);
  });

  const { globalData } = getApp();
  const topbarStyle = `height: ${globalData.navBarHeight}px; margin-top: ${globalData.statusBarHeight}px`;
  const mainStyle = `margin-top: ${globalData.navBarHeight + globalData.statusBarHeight + 12}px`;

  const fromPage = ref();
  const actionSheetOption = [{ name: '图片预览' }, { name: '重新上传' }];
  const actionSheetRef = ref(null);
  const licensePlatePopupRef = ref(null);
  const formRef = ref(null);
  const hasCameraAuth = ref(false);
  const drivingLicenseImg = ref('');
  const isVerticalImg = ref(false);

  const formData = reactive({
    id: '',
    drivingLicensePhoto: '',
    licensePlate: '',
    carType: '',
    owner: '',
    useNature: [],
    brandModel: '',
    identificationCode: '',
    engineCode: '',
    registerTime: '',
    peopleNum: '',
    casualtyAccident: 0,
    lastCheckTime: ''
  });

  const formRules = reactive({
    licensePlate: [{ type: 'string', required: true, message: '请输入车牌号', trigger: ['blur'] }],
    registerTime: [{ type: 'string', required: true, message: '请选择注册时间', trigger: ['blur'] }]
  });

  const handleOpenlicensePlatePopup = () => {
    licensePlatePopupRef.value.open(formData.licensePlate);
  };

  const handlePreviewOrTabkePhoto = () => {
    actionSheetRef.value.open();
  };

  const handleActionSheetSelect = item => {
    if(item.name === actionSheetOption[0].name) {
      uni.previewImage({
        urls: [drivingLicenseImg.value],
        current: drivingLicenseImg.value
      });
    }
    if(item.name === actionSheetOption[1].name) {
      handleTakePhoto();
    }
  }

  const handleOpenCameraAuth = () => {
    console.log('handleOpenCameraAuth');
    uni.openSetting(); //在onShow中将hasCameraAuth重新赋值
    // uni.openSetting({
    //   success: res => {
    //     console.log('handleOpenCameraAuth success');
    //     if (res.authSetting['scope.camera']) hasCameraAuth.value = true;
    //     else hasCameraAuth.value = false;
    //   },
    //   fail: () => {
    //     console.log('handleOpenCameraAuth fail');
    //   }
    // })
    // uni.authorize({
    //   scope: 'scope.camera',
    //   success: res => {
    //     console.log('handleOpenCameraAuth success');
    //     if (res['scope.camera']) hasCameraAuth.value = true;
    //     else hasCameraAuth.value = false;
    //   },
    //   fail: () => {
    //     console.log('handleOpenCameraAuth fail');
    //   }
    // })
  }

  const handleTakePhoto = () => {
    uni.getSetting({
      success(res) {
        console.log(res, res.authSetting['scope.camera']);
        if(res.authSetting['scope.camera']) {
          uni.navigateTo({
            url: '/pages/carCamera/carCamera?isShowEdit=0'
          })
        }else {
          uni.$u.toast('请先打开相机权限')
        }
      }
    })
  };

  const handleSubmit = () => {
    const submitData = { ...formData, useNature: Array.isArray(formData.useNature) ? formData.useNature[0] : '' };
    submitData.id = new Date().getTime();
    formRef.value.validate().then(async valid => {
      if (!valid) return;
      console.log('校验通过 submitData', submitData);
      await API.car.add(submitData)
      uni.$u.toast('提交成功');
      if (fromPage.value === 'car') uni.$emit('showNewCar', submitData.id)
      if (fromPage.value === 'carCard') uni.$emit('updateCarList')
      uni.navigateBack();
    }).catch(e => {})
  };

  const handleReturnPage = () => {
    uni.navigateBack();
  };
	
	const identifyDrivingLicense = async () => {
    const res = await API.car.identifyDrivingLicense(drivingLicenseImg.value);
    res.data.useNature = [res.data.useNature]
    Object.assign(formData, res.data)
	}

  const getDetail = async carId => {
    const res = await API.car.detail(carId);
    Object.assign(formData, res.data)
  }

  const checkIsVerticalImg = () => {
    if (!drivingLicenseImg.value) return false;
    uni.getImageInfo({
      src: drivingLicenseImg.value,
      success: res => {
        isVerticalImg.value = res.width / res.height < 1;
        console.log('getImageInfo', res, isVerticalImg.value);
      },
      fail: err => {
        console.error('获取图片信息失败:', err);
        isVerticalImg.value = false;
      }
    });
  };

  const useNatureOptions = [
    '非营运',
    '营运',
    '危险品运输',
    '警用',
    '消防',
    '救护',
    '工程抢险',
    '客运',
    '普通货运',
    '集装箱货车',
    '冷藏车',
    '罐车',
    '平板车',
    '自卸车',
    '特种车辆',
    '出租租赁',
    '公交',
    '出租',
    '租赁',
    '旅游客运',
    '预约出租客运',
    '网络预约出租客运',
    '非现场交通违法处理',
    '其他'
  ];
</script>

<style lang="scss" scoped>
  .add-car {
    height: 100vh;
    overflow: auto;
    position: relative;
    background: linear-gradient(to bottom, #0055a5 0, #f7f7f7 520rpx);

    .bg-logo {
      position: fixed;
      top: -3%;
      width: 680rpx;
      height: 600rpx;
      right: 0;
      pointer-events: none;
    }

    .topbar {
      color: white;
      z-index: 1;
      position: absolute;
      width: 100%;
      box-sizing: border-box;
      padding: 0 12px;
      @include flex-row(flex-start, center);

      &-returnBtn {
        @include flex-row(flex-start, center);

        &-text {
          margin-left: 4px;
          font-size: 14px;
        }
      }

      &-title {
        font-size: 18px;
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
      }
    }

    .main {
      @include card;
      padding: 16px;
      margin-bottom: calc(46px + 20px + 12px);
    }

    .driving-license {
      width: 100%;
      margin-bottom: 12px;

      &-title {
        @include flex-row(space-between, center);

        &-left {
          font-size: 15px;
          font-weight: bold;
        }

        &-right {
          font-size: 14px;
          text-decoration: underline; /* 添加下划线 */
          text-decoration-color: currentcolor; /* 设置下划线颜色与文本颜色相同 */
          color: $uni-color-primary;
        }
      }

      &-upload-img {
        position: relative;
        max-height: 320rpx;
        overflow: hidden;
        margin-top: 12px;
        border-radius: 12px;
      }

      .verticalImg {
        width: 320rpx;
        height: 640rpx;
        border-radius: 12px;
        transform: rotateZ(-90deg) translate(50%, 25%);
        box-shadow: 0px 4px 5px 0px rgba(0, 0, 0, 0.05);
      }

      .horizontalImg {
        width: 640rpx;
        height: 320rpx;
        border-radius: 12px;
        box-shadow: 0px 4px 5px 0px rgba(0, 0, 0, 0.05);
      }

      &-upload {
        position: relative;
        width: 100%;
        aspect-ratio: 2 / 1;
        margin-top: 12px;
        border-radius: 12px;
        background-color: #ebeff8;
        box-shadow: 0px 4px 5px 0px rgba(0, 0, 0, 0.02);

        &-img-placeholder {
          position: absolute;
          @include size(70%);
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          padding: 12px;
          box-sizing: border-box;
          background-color: white;
          border-radius: 12px;

          &-item {
            width: 50%;
            height: 100%;
          }
        }

        &-icon {
          position: absolute;
          // @include size(80rpx);
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }

    .bottom-btn {
      z-index: 9;
      @include bottom-btn;
      left: 12px;
      // transform: translateX(-50%);
      // color: white;
      // font-size: 16px;
      // letter-spacing: 8px;
      // position: fixed;
      // width: 95%;
      // left: 50%;
      // bottom: 20px;
      // height: 46px;
      // border-radius: 50px;
      // transform: translateX(-50%);
      // background: #1e7eba;
      // background: linear-gradient(to right, #1e7eba, #0558a8);
      // box-shadow: 0px 4px 10px 0px rgba(58, 134, 244, 0.302);
    }
  }
</style>
